<!--
 * @Descripttion: 
 * @version: 
 * @Author: weihua.yao
 * @Date: 2021-04-14 00:18:32
 * @LastEditTime: 2021-04-14 22:58:50
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <input type="file" id="upload">
  <script>
    const ACCEPT = ['image/jpg', 'image/png', 'image/jpeg']; // 限定图片文件类型
    const upload = document.getElementById('upload');
    const MAXSIZE = 1024 * 1024 * 3; // 限定图片最大容量
    const MAXSIZE_STR = '3MB';

    function convertImageToBase64(file, callback) {
      let reader = new FileReader();
      reader.addEventListener('load', function (e) {
        const base64Image = e.target.result; // 获取文件内容，等同于 reader.result
        callback(base64Image);
        reader = null;
      });
      reader.readAsDataURL(file); // 读取 file 对象中的内容
    }
    //压缩算法
    function compress(base64Image, callback) {
      let maxW = 1024;
      let maxH = 1024;
      const image = new Image();
      image.addEventListener('load', function () {
        let ratio; // 压缩比
        let needCompress = false; // 是否需要压缩
        if (maxW < image.naturalWidth) {
          needCompress = true;
          ratio = image.naturalWidth / maxW;
          maxH = image.naturalHeight / ratio;
        }
        if (maxH < image.naturalHeight) {
          needCompress = true;
          ratio = image.naturalHeight / maxH;
          maxW = image.naturalWidth / ratio;
        }
        if (!needCompress) {
          maxW = image.naturalWidth;
          maxH = image.naturalHeight;
        }
        const canvas = document.createElement('canvas');
        canvas.setAttribute('id', '__compress__');
        canvas.width = maxW;
        canvas.height = maxH;
        canvas.style.visibility = 'hidden';
        document.body.append(canvas);
        const ctx = canvas.getContext('2d');
        ctx.clearRect(0, 0, maxW, maxH);
        ctx.drawImage(image, 0, 0, maxW, maxH); // 渲染图片
        const compressImage = canvas.toDataURL('image/jpeg', 0.9); // 压缩图片
        callback&&callback(compressImage);
        // const _image = new Image();
        // _image.src = compressImage;
        // document.body.appendChild(_image);
        canvas.remove(); // 移除 canvas
      });
       image.src = base64Image; // 将图片设置到 image 的 src 属性中
      // document.body.appendChild(image);
    }

    function uploadImage(compressImage) {
      console.log('upload image to server...', compressImage);
    }
    upload.addEventListener('change', function (e) {
      const [file] = e.target.files; // const file = e.target.files[0] 
      if (!file) return
      const {
        type: fileType,
        size: fileSize
      } = file
      // 图片类型检查
      if (!ACCEPT.includes(fileType)) {
        alert(`不支持上传格式文件！`);
        upload.value = '';
        return;
      }
      // 图片大小检查
      if (fileSize > MAXSIZE) {
        alert('文件超出' + MAXSIZE_STR + '！');
        upload.value = '';
        return;
      }
      // 压缩文件
      convertImageToBase64(file, (base64Image) => compress(base64Image, uploadImage));
    })
  </script>
</body>

</html>